/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.personalNotes.client;


import com.gadglet.client.gwt.GadgetNativeUtils;
import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.core.ui.ShareWithIcon;
import com.gadglet.client.gwt.ui.CanvasViewMainPanel;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.SimpleDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.gadgets.personalNotes.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqTypes;
import com.gadglet.params.SortTypes;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.ContentSection;
import com.google.gwt.gadgets.client.Gadget.ContentType;
import com.google.gwt.gadgets.client.Gadget.InjectContent;
import com.google.gwt.gadgets.client.PreferencesFeature;
import com.google.gwt.gadgets.client.PreferencesProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * The Gadget Canvas view 
 * <p>
 * In this view user can:
 * <li> Edit profile
 * <li> Invite and accept friends
 * <li> Add personal notes
 * <li> Delete personal notes
 * <li> Share personal notes
 * <li> Edit/Update Personal notes 
 * 
 *
 */
@InjectContent(files = "canvas.html")
@ContentType(type = "html", views = { "canvas" })
public class PersonalNotesCanvasView extends
ContentSection<PersonalNotesGadget> {
	private DebugDialogBox debug = null;

	/**
	 *  Query object use to create a request for personal notes list
	 */
	final GadgletQuery viewPersonalNotesQry = new GadgletQuery(
			ReqTypes.MINGLET);
	
	/**
	 * Request object used to send a request to the gadget server
	 *  and process the results
	 */
	final ViewPersonalNotes viewPersonalNotesRequest = new ViewPersonalNotes(
			viewPersonalNotesQry);

	/**
	 * Query object used to build "add", "update" and "delete" requests
	 */
	final GadgletQuery changePersonalNoteQry = new GadgletQuery(
			ReqTypes.MINGLET);
	
	/**
	 * Request Object used to perform "add" and "delete" requests
	 * and process the results
	 */
	final GadgletRequest addDeletePersonalNoteRequest = new AddDeletePersonalNotes(
			changePersonalNoteQry);

	/**
	 *  Request Object used to perform "update"  requests
	 */
	final GadgletRequest updatePersonalNoteRequest = new UpdatePersonalNotes(
			changePersonalNoteQry);
	
	
	/**
	 * The result grid 
	 */
	final Grid results = new Grid();
	
	/**
	 * Container for the "prev" "next" buttons
	 */
	protected final HorizontalPanel paging = new HorizontalPanel();

	final Button prevButton = new Button();
	final Button nextButton = new Button();
	final PreferencesFeature  prefsUtils = PreferencesProvider.get();

	final SimpleDialogBox serverMessage = SimpleDialogBox
	.getMesseageDialogBox();
	

	@Override
	public void init(PersonalNotesGadget gadget) {
		
		results.setCellSpacing(0);
		results.setCellPadding(2);
		
		addDeletePersonalNoteRequest.setMethodType(MethodType.POST);
		
		debug = DebugDialogBox.getErrorNotifier();

		prevButton.setText(prefsUtils.getMsg("gadgetLabelPrevious"));
		nextButton.setText(prefsUtils.getMsg("gadgetLabelNext"));
	
		

		final CanvasViewMainPanel mainPanel = new CanvasViewMainPanel();

		final HorizontalPanel addItemPanel = new HorizontalPanel();
		final DisclosurePanel addDisclosurePanel = new DisclosurePanel(
				prefsUtils.getMsg("gadgetLabelAdd"));
		final TextArea message = new TextArea();
		
		message.setSize(GadgetNativeUtils.getGadgetWidth() / 2 + "px","200px");
		
		final VerticalPanel priority = new VerticalPanel();
		final RadioButton highPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelHigh"));
		final RadioButton medPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelMedium"));
		final RadioButton lowPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelLow"));
		lowPriority.setValue(true);
		priority.add(highPriority);
		priority.add(medPriority);
		priority.add(lowPriority);

		final Button saveButton = new Button(
				prefsUtils.getMsg("gadgetLabelSave"));
		final PrioritySelection selection = new PrioritySelection(
				viewPersonalNotesQry, viewPersonalNotesRequest);
		addItemPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		addItemPanel.add(message);
		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(priority);
		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(saveButton);
		
		/**  This code is designed to demonstrate a ("custom")request
		*	to a server side method that is defined on the Gadget level
		*	the name of the server side method is explicitly set "doDeleteAll"
		*	with the  setContentActoinName() method.
		*	@ see com.gadglet.gadgets.personalNotes.server.RequestHandler.deleteAll()
			
			to test enable both client and server-side code  
		*/
		
		
		final Button deleteAllButton = new Button(prefsUtils.getMsg("gadgetLabelDelete")+ " " + prefsUtils.getMsg("gadgetLabelAll"));
		addItemPanel.add(UIUtils.getSpace());
		addItemPanel.add(deleteAllButton);
	
		
		deleteAllButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changePersonalNoteQry.setContentActoinName("doDeleteAll");
				changePersonalNoteQry.clearParamList();


				addDeletePersonalNoteRequest.makeRequest();
		

			}
		});

		addDisclosurePanel.add(addItemPanel);
		addDisclosurePanel.setHeader(new HTML(prefsUtils
				.getMsg("gadgetLabelAdd")));

		mainPanel.add(addDisclosurePanel);

		mainPanel.add(selection.getPanel());

		mainPanel.add(results);

		RootPanel.get().add(mainPanel.getGadgetPanel());

		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changePersonalNoteQry.setRequestAction(ReqActionTypes.ADD);
				changePersonalNoteQry.clearParamList();

				String priority = "";
				if (highPriority.getValue())
					priority = "1";
				else if (medPriority.getValue())
					priority = "2";
				else
					priority = "3";

				changePersonalNoteQry.addParam(Params.PRIORITY.getParamName(), priority);
				changePersonalNoteQry.addParam(Params.MESSAGE.getParamName(),
						message.getValue());

				addDeletePersonalNoteRequest.makeRequest();
				message.setValue("");

			}
		});

		viewPersonalNotesQry.setRequestAction(ReqActionTypes.VIEW);
		viewPersonalNotesQry.addSortBy("creation", SortTypes.ASC);
		viewPersonalNotesQry
		.setReturnField("personalNotesMessage,creation");
		viewPersonalNotesQry.setStartItemsFrom(0);
		viewPersonalNotesQry.setItemsNum(20);
		viewPersonalNotesRequest.makeRequest();

		prevButton.setVisible(false);
		prevButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewPersonalNotesQry.setStartItemsFrom(viewPersonalNotesQry
						.getStartFrom() - viewPersonalNotesQry.getItemNum());
				viewPersonalNotesRequest.makeRequest();

			}

		});
		paging.add(prevButton);

		nextButton.setVisible(false);
		nextButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewPersonalNotesQry.setStartItemsFrom(viewPersonalNotesQry
						.getStartFrom() + viewPersonalNotesQry.getItemNum());
				viewPersonalNotesRequest.makeRequest();

			}

		});
		paging.add(nextButton);

	}

	public class ViewPersonalNotes extends GadgletRequest {
		GadgletResponse jResponse;

		ViewPersonalNotes(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			jResponse = data;

			results.resize(0, 4);
			results.clear();
			
			if (jResponse.isSuccessful() && jResponse.getRootItemsNum()>0) {
				
				results.resize(1, 4);
				DeleteImage deleteImage = null;
				int index;
				String rowStyle = null;
				
				for (index = 0; index < jResponse.getRootItemsNum(); index++) {

				
					if (index%2==0)
						rowStyle = "gridRowShadow";
					else
						rowStyle = "gridRowNoShadow";
					results.getRowFormatter().setStyleName(index, rowStyle);
					

					results.setWidget(index, 0, new Image(GadgetUtils.getGadgetIconURL(jResponse.getStringItemValue(
							Params.PRIORITY.getParamName(), index), null, false)));
					
					
					
					final Label msg = new Label();
					
					final String noteId = jResponse.getItemKeyValue(index);
					
					msg.setText(jResponse.getStringItemValue(
							Params.MESSAGE.getParamName(), index));
					VerticalPanel msgItem= new VerticalPanel();
					msgItem.add(msg);
					
					final TextArea msgEdit = new TextArea();
					
					if(data.isUpdatePermitted(index)){
						msgEdit.setWidth("500px");
						msgEdit.setVisible(false);
						msgEdit.setText(jResponse.getStringItemValue(
								Params.MESSAGE.getParamName(), index));
										
						msgItem.add(msgEdit);
										
						msg.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								msgEdit.setVisible(true);
								msg.setVisible(false);
										
							}

						});
						
						msgEdit.addBlurHandler(new BlurHandler(){
							@Override
							public void onBlur(BlurEvent event) {
								// ignore empty
								if(msgEdit.getText().length()==0){
									msgEdit.setVisible(false);
									msg.setVisible(true);
									msgEdit.setText(msg.getText());
								}
								else
								{
									msgEdit.setVisible(false);
									msg.setText(msgEdit.getText());
									msg.setVisible(true);
									
									changePersonalNoteQry.clearParamList();
									
									changePersonalNoteQry
									.setRequestAction(ReqActionTypes.UPDATE);
									
									changePersonalNoteQry
									.setRequestItemkey(noteId);
																							
									changePersonalNoteQry.addParam(Params.MESSAGE.getParamName(),
											msgEdit.getText());
									
									updatePersonalNoteRequest.makeRequest();
								}
								
								
						}});
					}
					
				
					results.setWidget(index, 1, msgItem);
					
					
					deleteImage = new DeleteImage(GadgetUtils.getGadgetIconURL(
							"delete", null, false),
							jResponse.getItemKeyValue(index));
					
					
					if(data.isDeletePermitted(index)){
					
						deleteImage.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								changePersonalNoteQry.clearParamList();
								
								changePersonalNoteQry
								.setRequestAction(ReqActionTypes.DELETE);
								
								changePersonalNoteQry
								.setRequestItemkey(((DeleteImage) event
										.getSource()).getItemID());
								addDeletePersonalNoteRequest.makeRequest();
	
							}
	
						});
						
					}
					else{
						// delete: "hide" sharing 
						
						deleteImage.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								changePersonalNoteQry.clearParamList();
								
								changePersonalNoteQry
								.setRequestAction(ReqActionTypes.DELETE);
								changePersonalNoteQry.setCustomtContentName("sharing");
								changePersonalNoteQry
								.setRequestItemkey(((DeleteImage) event
										.getSource()).getItemID());
								addDeletePersonalNoteRequest.makeRequest();
								changePersonalNoteQry.setCustomtContentName(null);
	
							}
	
						});
					}
				
				results.setWidget(index, 2, deleteImage);	
					
				if(data.isSharePermitted(index)){
					
											
						ShareWithIcon shareWithIcon = new ShareWithIcon(jResponse.getItemKeyValue(index),msg.getText());
						Image shareIcon = shareWithIcon.getImage();
						
						results.setWidget(index, 3, shareIcon);
					}
				else{
					String nick = data.getStringItemValue(ProfileFields.PROFILE_NICKNAME.getParamName(),index);
					String photo = data.getStringItemValue(ProfileFields.PROFILE_THUMBNAILURL.getParamName(),index);
					
					HorizontalPanel profile = new HorizontalPanel();
					profile.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
					if(nick!=null)
						if(nick!=null){								
							profile.add(new HTML(prefsUtils.getMsg("gadgetLabelSharedBy")+":"));
							profile.add(UIUtils.getSpace());
							profile.add(new Label(nick));

						}
					if(photo!=null && !photo.isEmpty()){
						profile.add(UIUtils.getSpace());
						Image photoImg = new Image(photo);
						photoImg.setPixelSize(40, 40);
						profile.add(photoImg);
						
					}
					
					results.setWidget(index, 3, profile);
					
				}
					
					
					results.resize(index + 3, 4);

				}
				

				if (viewPersonalNotesQry.getStartFrom() > 0)
					prevButton.setVisible(true);
				else
					prevButton.setVisible(false);

				if (jResponse.hasMoreItems())
					nextButton.setVisible(true);
				else
					nextButton.setVisible(false);

				results.setWidget(index, 0, paging);

			}

		}
	}

	/**
	 * Request object for "add" and "delete"
	 *
	 */
	public class AddDeletePersonalNotes extends GadgletRequest {
		AddDeletePersonalNotes(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewPersonalNotesRequest.makeRequest();
			} else {

				serverMessage
				.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}
	
	/**
	 * Request object for "update"
	 *
	 */
	public class UpdatePersonalNotes extends GadgletRequest {
		UpdatePersonalNotes(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
						
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// do nothing
			} else {

				serverMessage
				.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

}
